
import os
import os.path
import glob
import re


def saveProject(folder, number=5, stem="qgs-save"):
    """ rename any older backups and return new file name """
    files = allFiles(folder,stem)
    print "allfiles: "+",".join([str(z) for z in files])
    if len(files) == 0:
        # make backup number 1
        return (stem+"-1.qgs",None)
    
    
    fcodes = [(z,code(z)) for z in files]
    fcodes.sort(cmp = lambda x,y: cmp(x[1],y[1]))
    newIndex = fcodes[-1][1] + 1
    fails = []
    print "fcodes has length %s and number = %s" % (len(fcodes),number)
    if len(fcodes) >= number:
        # delete oldest few
        zap = fcodes[:-(number-1)]
        removes = [z[0] for z in zap]
        print "removes:"+",".join([str(z) for z in removes])
        for f in removes:
            try:
                os.remove(f)
            except:
                fails.append(f)
    print "fails: "+",".join([str(z) for z in fails])
    return (stem+"-%d.qgs" % newIndex, fails)
    

def allFiles(folder,stem):
    filePattern = stem+"-[0-9]*.qgs"
    pathPattern = os.path.join(folder,filePattern)
    files=glob.glob(pathPattern)
    return files

def code(path):
    n=re.compile('-([0-9]*).qgs$')
    m=n.search(path)
    icode = int(m.groups()[0])
    
    return icode

def main():
    nextFile = saveProject(".")
    print "now creating ",nextFile

if __name__=="__main__":
    main()
